#!/usr/bin/env python3
"""
Resource-agents MCP Server

面向 resource-agents 软件包的 MCP Server，提供对 resource-agents 相关系统服务的管理功能。

MCP tools 列表：
1. ldirectord_service_management - 管理 ldirectord 服务的启动、重载和状态检查
   参数：action (str) - 要执行的操作：start|reload|status
   返回：统一的 JSON 结构，包含命令执行结果

2. resource_agents_deps_target_management - 管理 resource-agents-deps.target 的执行和重载
   参数：action (str) - 要执行的操作：start|reload|status
   返回：统一的 JSON 结构，包含命令执行结果
"""

import subprocess
import json
from typing import Dict, Any
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("Resource-agents MCP Server")

@mcp.tool()
def ldirectord_service_management(action: str) -> Dict[str, Any]:
    """
    管理 ldirectord 服务的启动、重载和状态检查
    
    参数:
        action (str): 要执行的操作，可选值：
            - "start": 启动 ldirectord 服务
            - "reload": 重载 ldirectord 服务（包括修改配置和重新加载）
            - "status": 检查 ldirectord 服务状态
    
    返回:
        Dict[str, Any]: 统一的执行结果结构
            {
                "success": bool,      # 操作是否成功
                "command": str,       # 执行的命令
                "exit_code": int,     # 命令退出码
                "stdout": str,        # 标准输出
                "stderr": str         # 标准错误
            }
    """
    try:
        if action == "start":
            # 启动 ldirectord 服务
            result = subprocess.run(
                ["systemctl", "start", "ldirectord.service"],
                capture_output=True,
                text=True,
                timeout=30
            )
        elif action == "reload":
            # 修改服务配置并重载
            # 首先修改 ExecStart 配置
            sed_result = subprocess.run(
                ["sed", "-i", "s|ExecStart=/usr/sbin/ldirectord|ExecStart=/usr/sbin/ldirectord -d|g", 
                 "/usr/lib/systemd/system/ldirectord.service"],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            if sed_result.returncode != 0:
                return {
                    "success": False,
                    "command": "sed -i 's|ExecStart=/usr/sbin/ldirectord|ExecStart=/usr/sbin/ldirectord -d|g' /usr/lib/systemd/system/ldirectord.service",
                    "exit_code": sed_result.returncode,
                    "stdout": sed_result.stdout,
                    "stderr": sed_result.stderr
                }
            
            # 重新加载守护进程配置
            daemon_reload_result = subprocess.run(
                ["systemctl", "daemon-reload"],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            if daemon_reload_result.returncode != 0:
                return {
                    "success": False,
                    "command": "systemctl daemon-reload",
                    "exit_code": daemon_reload_result.returncode,
                    "stdout": daemon_reload_result.stdout,
                    "stderr": daemon_reload_result.stderr
                }
            
            # 重载 ldirectord 服务
            result = subprocess.run(
                ["systemctl", "reload", "ldirectord.service"],
                capture_output=True,
                text=True,
                timeout=30
            )
        elif action == "status":
            # 检查服务状态
            result = subprocess.run(
                ["systemctl", "status", "ldirectord.service"],
                capture_output=True,
                text=True,
                timeout=30
            )
        else:
            return {
                "success": False,
                "command": f"ldirectord_service_management with action={action}",
                "exit_code": 1,
                "stdout": "",
                "stderr": f"Invalid action: {action}. Supported actions: start, reload, status"
            }
        
        return {
            "success": result.returncode == 0,
            "command": f"ldirectord_service_management action={action}",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": f"ldirectord_service_management with action={action}",
            "exit_code": 124,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": f"ldirectord_service_management with action={action}",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Error executing command: {str(e)}"
        }

@mcp.tool()
def resource_agents_deps_target_management(action: str) -> Dict[str, Any]:
    """
    管理 resource-agents-deps.target 的执行和重载
    
    参数:
        action (str): 要执行的操作，可选值：
            - "start": 启动 resource-agents-deps.target
            - "reload": 重载 resource-agents-deps.target
            - "status": 检查 resource-agents-deps.target 状态
    
    返回:
        Dict[str, Any]: 统一的执行结果结构
            {
                "success": bool,      # 操作是否成功
                "command": str,       # 执行的命令
                "exit_code": int,     # 命令退出码
                "stdout": str,        # 标准输出
                "stderr": str         # 标准错误
            }
    """
    try:
        if action == "start":
            # 启动 resource-agents-deps.target
            result = subprocess.run(
                ["systemctl", "start", "resource-agents-deps.target"],
                capture_output=True,
                text=True,
                timeout=30
            )
        elif action == "reload":
            # 重载 resource-agents-deps.target
            result = subprocess.run(
                ["systemctl", "reload", "resource-agents-deps.target"],
                capture_output=True,
                text=True,
                timeout=30
            )
        elif action == "status":
            # 检查 target 状态
            result = subprocess.run(
                ["systemctl", "status", "resource-agents-deps.target"],
                capture_output=True,
                text=True,
                timeout=30
            )
        else:
            return {
                "success": False,
                "command": f"resource_agents_deps_target_management with action={action}",
                "exit_code": 1,
                "stdout": "",
                "stderr": f"Invalid action: {action}. Supported actions: start, reload, status"
            }
        
        return {
            "success": result.returncode == 0,
            "command": f"resource_agents_deps_target_management action={action}",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": f"resource_agents_deps_target_management with action={action}",
            "exit_code": 124,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": f"resource_agents_deps_target_management with action={action}",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Error executing command: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()